layui.use(['form', 'upload'], function () {
    const form = layui.form,
        upload = layui.upload,
        $ = layui.jquery;

    // 初始化
    $(function () {
        setTimeout(function () {
            const materialCode = $("#code").val();
            if (materialCode === undefined || materialCode === "") {
                layer.msg("页面出错，请返回并重新加载");
                return;
            }
            $.get(URL_SYSTEM_MATERIAL + "/" + materialCode, function (res) {
                if (res.code === 0) {
                    form.val('material-val-filter', res.data);

                    renderImgBox(res.header.domain, res.data.materialImg);
                }
            });
        }, 50);
    });

    // 取消按钮
    $("#btn-material-cancel").click(function () {
        const index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
    });

    // 多图片上传
    upload.render({
        elem: '#ID-upload-btn',
        multiple: true,
        auto: false,
        choose: function (obj) {
            let files = obj.pushFile();
            if (files.length <= 0) {
                return;
            }
            // 预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                uploadToQiniu(file);
            });
        },
        done: function (res) {
            // 上传完毕
        },
        allDone: function (obj) {
            console.log(obj.total); // 上传的文件总数
            console.log(obj.successful); // 上传成功的文件数
            console.log(obj.failed); // 上传失败的文件数
        }
    });

    form.on('submit(material-submit)', function (data) {
        let url, method;
        if (isEmpty(data.field.code)) {
            url = URL_SYSTEM_MATERIAL;
            method = 'post';
        } else {
            url = URL_SYSTEM_MATERIAL + '/' + data.field.code;
            method = 'put';
        }
        $.ajax({
            type: method,
            url: url,
            data: JSON.stringify({
                ...data.field
            }),
            headers: COMMON_HEADERS,
            success: function (res) {
                if (res.code === 0) {
                    const index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                    parent.layer.msg(OPERATION_SUCCESS.MESSAGE, {
                        time: 2000
                    });
                    parent.layui.table.reload(TABLE_ID_MATERIAL);
                } else {
                    layer.alert(JSON.stringify(res), OPERATION_SUCCESS.ICON_CONTENT);
                }
            },
            error: function (res) {
                layer.alert(JSON.stringify(res), OPERATION_SUCCESS.ICON_CONTENT);
            }
        });
        // 防止表单的重复提交
        return false;
    });

    function renderImgBox(domain, imgStr) {
        if (isEmpty(imgStr) || isEmptyArray(imgStr.split(","))) {
            return;
        }
        imgStr.split(",").forEach((item) => $('#upload-preview').append(getImgContent(domain, item)))
    }

    function getQiniuToken(file) {
        let suffix = file.name.substring(file.name.lastIndexOf("."), file.name.length);
        let token;
        $.ajax({
            async: false,
            type: 'get',
            url: '/system/upload/token',
            data: {"suffix": suffix},
            success: function (res) {
                token = res.data;
            }
        });
        return token;
    }

    function uploadToQiniu(file) {
        // 调用七牛云sdk进行上传
        let qiniuToken = getQiniuToken(file);

        let observer = {                     //设置上传过程的监听函数
            next(result) {                  //上传中(result参数带有total字段的 object，包含loaded、total、percent三个属性)
                Math.floor(result.total.percent);//查看进度[loaded:已上传大小(字节);total:本次上传总大小;percent:当前上传进度(0-100)]
            },
            error(err) {
                alert(err.message);
            },
            complete(res) {
                $('#upload-preview').append(getImgContent(qiniuToken.domain, qiniuToken.imgUrl));

                // 将图片地址暂存到变量，保存时再进行提交（不存储domain，方便更换）
                let materialImgElm = $('#materialImg');
                if (materialImgElm.val() === undefined || materialImgElm.val() === null || materialImgElm.val() === '') {
                    materialImgElm.val(qiniuToken.imgUrl);
                } else {
                    materialImgElm.val(materialImgElm.val() + ',' + qiniuToken.imgUrl);
                }
            }
        };
        let putExtra = {
            fname: "",                          //原文件名
            params: {},                         //用来放置自定义变量
            mimeType: null                      //限制上传文件类型
        };
        let config = {
            region: qiniu.region.z2,            //存储区域(z0:代表华东;z2:代表华南,不写默认自动识别)
            concurrentRequestLimit: 3           //分片上传的并发请求量
        };
        let observable = qiniu.upload(file, qiniuToken.imgUrl, qiniuToken.token, putExtra, config);
        let subscription = observable.subscribe(observer);
        // 取消上传
        // subscription.unsubscribe();
    }

    function getImgContent(domain, imgUrl) {
        return '<img src="' + domain + imgUrl + '" fileName="' + imgUrl + '" alt="' + imgUrl + '" title="点击删除" class="img" onclick="delMultipleImg(this)">'
    }
})

function delMultipleImg(this_img) {
    // 获取文件名
    let fineName = this_img?.attributes?.fileName?.nodeValue;
    // 删除元素
    this_img.remove();
    let materialImgElm = $('#materialImg');
    if (isEmpty(materialImgElm.val())) {
        return;
    }
    let imgArray = materialImgElm.val().split(',');
    // 删除数据
    let index = imgArray.findIndex((value, index, array) => value === fineName);
    imgArray.splice(index, 1);
    materialImgElm.val(imgArray.join(','));
}